package com.lora.communication.mqtt;

import com.lora.util.StringUtil;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * mqtt链接工具类,创建一个mqtt链接实例
 */
@Component
@PropertySource(value = "classpath:application-dev.properties")
public class MqttConnectUtil {
    @Value("${mqtt.url}")
    private String mqurl;

    private MqttClient mqttClient=null;

    private final Logger logger = LoggerFactory.getLogger(MqttConnectUtil.class);

    private MqttClient create(String clentid, MqttCallback emqttdCallback){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        // 2.实例化mqtt客户端
        try {
            if(mqurl==null||mqurl.trim().equals("")){
                throw new RuntimeException("找不到对应的mqtt协议中间件");
            }
            options.setUserName("wangw");
            options.setPassword("ww1030".toCharArray());
            options.setCleanSession(true);
            options.setAutomaticReconnect(true);
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(0);
            MqttClient client = new MqttClient(mqurl,clentid,new MemoryPersistence());
            client.setCallback(emqttdCallback); //设置回调处理类
            client.connect(options);
            logger.info("mqtt协议中间件加载成功");
            return client;
        } catch (MqttException e) {
            logger.info("mqtt协议中间件加载失败");
            e.printStackTrace();
        }
        return null;
    }

    public MqttClient getMqttClient(){
        if(mqttClient==null){
            synchronized (this) {
                if(mqttClient==null) {
                    mqttClient = create(StringUtil.getStringRandom(10), new LoraMqttCallback());
                }
            }
        }
        return mqttClient;
    }
}
